package com.ssm.controller;

import com.ssm.pojo.Customer;
import com.ssm.pojo.User;
import com.ssm.service.CustomerService;
import com.ssm.service.UserService;
import org.apache.catalina.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private CustomerService customerService;

    @RequestMapping(value="/login",method = RequestMethod.GET)
    public String tologin(){
        return "login";
    }

    @RequestMapping(value = "/login/success",method = RequestMethod.POST)
    public String success(HttpSession session, String userName, String password, Short type){
        return "redirect:/index";
    }
    @RequestMapping(value="/valid",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> valid(HttpSession session,String userName, String password, Short type){
        Customer customer =null;
        User user = null;
        boolean flag = false;
        Map<String,String> map = new HashMap<String, String>();
        if(type==1){
            customer = customerService.selectByNameAndPassword(userName,password);
            if(customer!=null){
                flag = true;
            }
        }else{
            user = userService.selectByNameAndPassword(userName,password);
            if(user != null){
                flag = true;
            }
        }
        if(flag){
            map.put("status","true");
            map.put("msg","登陆成功");
            session.setAttribute("customer",customer);
            session.setAttribute("user",user);
            session.setAttribute("type",type);
        }else {
            map.put("status","false");
            map.put("msg","账号或密码错误");
        }
        return map;
    }
    @RequestMapping(value = {"/","/index"},method = RequestMethod.GET)
    public String index(HttpSession session, Model model){
//        Customer customer= (Customer) session.getAttribute("customner");
//        User user = (User) session.getAttribute("user");
//        Integer type =(Integer) session.getAttribute("type");
//        model.addAttribute();
        return "main";
    }

    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(HttpSession session){
        session.removeAttribute("user");
        session.removeAttribute("customer");
        session.removeAttribute("type");
        return "login";
    }

    @RequestMapping("/welcome")
    public String welcome(){
        return "welcome";
    }



}


